﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Faml.Frontend
{
    public abstract class ParserInput
    {
        protected string name = String.Empty;
        private int line = 1;
        private int col = 1;
        private Stack<int> putback = new Stack<int>();

        /// <summary>Reads next char from input</summary>
        /// <returns>Char code or -1 in case of EOF</returns>
        protected abstract int ReadChar();

        /// <summary>Returns current location in parser source</summary>
        public Location CurrentLocation
        {
            get
            {
                return new Location(name, line, col);
            }
        }

        public int GetChar()
        {
            if (putback.Count > 0)
                return putback.Pop();
            else
            {
                int ch = ReadChar();
                if (ch == (int)'\n')
                {
                    line++;
                    col = 1;
                }
                else
                    col++;
                return ch;
            }
        }

        public void PutBack(char ch)
        {
            putback.Push((int)ch);
        }
    }

    public class StringParserInput : ParserInput
    {
        private string s;
        private int pos;

        public StringParserInput(string s)
        {
            this.s = s;
            this.pos = 0;
        }

        protected override int ReadChar()
        {
            if (pos >= s.Length)
                return -1;
            else
                return (int)s[pos++];
        }
    }

    public class StreamParserInput : ParserInput
    {
        private Stream stream;

        public StreamParserInput(Stream stream)
        {
            this.stream = stream;
        }

        public StreamParserInput(string path)
        {
            name = path;
            stream = File.OpenRead(path);
        }

        protected override int ReadChar()
        {
            return stream.ReadByte();
        }
    }

    public class TextReaderParserInput : ParserInput
    {
        private TextReader reader;

        public TextReaderParserInput(TextReader tr)
        {
            reader = tr;
        }

        public string SourceName
        {
            set
            {
                name = value;
            }
            get
            {
                return name;
            }
        }

        protected override int ReadChar()
        {
            return reader.Read();
        }
    }
}